#!/usr/bin/env python
#encoding=utf-8

import argparse

ap= argparse.ArgumentParser(description='barh')
ap.add_argument('file', help='q file')
ap.add_argument('order', help='order file')
ap.add_argument('-p', '--prefix', help='out prefix', default='1')
args= ap.parse_args()


import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# import matplotlib.colors as colors
import matplotlib.cm as cm
from matplotlib import rcParams
fontsize = 5
rcParams['font.size'] = fontsize

dat = pd.read_table(args.file, header=None, index_col=0)
dat = dat.loc[~ dat.index.duplicated()]

order = pd.read_table(args.order, header=None, index_col=0)
order = order.loc[~ order.index.duplicated()]

dat = dat.loc[order.index.intersection(dat.index)[::-1]]

if order.shape[1] != 0:
    labels = dat.index + '; ' + order.loc[dat.index].apply(lambda x: '; '.join(x), axis=1)
else:
    labels = dat.index


# ind = np.arange(dat.shape[1])    # the x locations for the groups
width = 1 # the width of the bars: can also be len(x) sequence
width1 = .03
# p1 = plt.bar(ind, menMeans, width, color='#d62728', yerr=menStd)

# color = colors.Colormap('jet', dat.shape[1])
colors = cm.get_cmap('gist_rainbow')(np.linspace(0, 1, dat.shape[1]))

# fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(18, 1.1*width1*dat.shape[0]))



size = (10, 10)

fig, ax = plt.subplots(nrows=1, ncols=1, figsize=size)

# plt.figure(figsize=(12, width*dat.shape[0]))


ax.barh(list(range(dat.shape[0])), dat.iloc[:, 0].values, height=width, color=colors[0])
for i, color in zip(list(range(1, dat.shape[1])), colors[1:]):
    ax.barh(list(range(dat.shape[0])), dat.iloc[:, i].values, height=width, left=dat.iloc[:, :i].sum(axis=1), color=color)

# plt.ylabel('Scores')
# plt.title('Scores by group and gender')
# plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
# plt.yticks(dat.index.values)
# ax.set_yticklabels(dat.index.values)
ax.set_ylim(-1, dat.shape[0])
ax.set_xlim(0, 1)

percent1, size1, percent2, pt = 0.8, fontsize, 1.1, 72
h = size[1]
num_labels = percent1 * h * pt / size1 /percent2
num_labels = int(num_labels)
# num_labels = 50
num_lin = np.linspace(0, dat.shape[0]-1, num_labels).round().astype(np.int)

plt.setp(ax, yticks=num_lin, yticklabels=labels.values[num_lin])
# plt.legend((p1[0], p2[0]), ('Men', 'Women'))
# plt.show()

plt.grid(True, axis='x', alpha=.5, linewidth=1)
# ax.set_xlabel('beta value')
# ax.set_ylabel('frequency')

fig.subplots_adjust(top=0.9, bottom=0.1, left=0.35, right=0.9)

plt.savefig(args.prefix + '.q_bar1.pdf')